﻿// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System;
using System.Windows.Media;
using System.Windows.Media.Imaging;

using Coding4Fun.Kinect.Wpf;
using Microsoft.Kinect;

namespace Coding4Fun.Chair.Kinect
{
    /// <summary>
    /// Represents a Natural User Interface (image and depth) sensor handler.
    /// </summary>
    public class DepthCamera : INuiSensor
    {
    	public event EventHandler<FrameReadyEventArgs> FrameReady;

		BitmapSource _colorImage;
    	Sensor _sensor = new Sensor();

    	const int MinDistance = 950;
		double _bitmapScale = 1;
    	public void Start()
    	{
			Start(1);
    	}

		public void Start(double targetImageScale)
    	{
			var scale = 320f;


			_bitmapScale = targetImageScale / scale;

            _sensor.AllFramesReady += new EventHandler<AllFramesReadyEventArgs>(_sensor_AllFramesReady);
            _sensor.Start(); 
			
    	}

        void _sensor_AllFramesReady(object sender, AllFramesReadyEventArgs e)
        {
            _sensor_ColorFrameReady(e);
            _sensor_DepthFrameReady(e);
        }

    	public void Stop()
    	{
            _sensor.Stop(); 
    	}

		void _sensor_ColorFrameReady(AllFramesReadyEventArgs e)
		{
            using (ColorImageFrame colorFrame = e.OpenColorImageFrame())
            {
                _colorImage = colorFrame.ToBitmapSource(); 
            }
		}


		void _sensor_DepthFrameReady(AllFramesReadyEventArgs e)
		{
            using (DepthImageFrame depthFrame = e.OpenDepthImageFrame())
            {
                var imageWidth = depthFrame.Width;
                var imageHeight = depthFrame.Height; 

                var imageHeightWithMargin = imageHeight - 50;


                var depthArray = depthFrame.ToDepthArray();
                var rightHandOffset = imageWidth / 2;
                var leftHand = depthArray.GetMidpoint(imageWidth, imageHeight, 0, 0, rightHandOffset, imageHeightWithMargin, MinDistance);
                var rightHand = depthArray.GetMidpoint(imageWidth, imageHeight, rightHandOffset, 0, imageWidth, imageHeightWithMargin, MinDistance);

                leftHand.X *= _bitmapScale;
                leftHand.Y *= _bitmapScale;

                rightHand.X *= _bitmapScale;
                rightHand.Y *= _bitmapScale;

                var args = new FrameReadyEventArgs
                {
                    DepthBitmap = depthArray.ToBitmapSource(imageWidth, imageHeight, MinDistance, Color.FromArgb(255, 255, 0, 0)),
                    ImageBitmap = _colorImage,
                    LeftHand = leftHand,
                    RightHand = rightHand
                };

                FrameReady(this, args);

            }


			

		}

		
    }
}

